package neanda.engine.core;

import java.util.Vector;

import neanda.engine.core.window.Window;
import neanda.engine.util.log.Log;

public class EngineController implements Runnable
{
	private static Window window;
	
	private static Vector<Gameable> listener = new Vector<Gameable>();
	private static long frame_count = 0L;

	private static long delta = 0;
	private static long last = 0;
	private static long fps = 0;

	private static Log log = new Log();
	
	public static void initialization()
	{
		log.setActiv(false);
		log.logMessage("Init start");
		for(Gameable list:listener)
		{
			list.initialization();
		}
	}
	
	public static void frame(long delta)
	{
		log.logMessage("Frame start");
		for(Gameable list:listener)
		{
			list.frame(delta);
		}
	}
	
	public static void addGameableListener(Gameable gameable)
	{
		listener.add(gameable);
	}

	@Override
	public void run()
	{
		initialization();
		while(true)
		{
			controlFps();
			frame(delta);
			try
			{
				Thread.sleep(9);
			} 
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
	}
	
	private void controlFps()
	{
		delta = System.nanoTime() - last;
		last = System.nanoTime();
		fps = ((long) 1e9) / delta; 
		log.logMessage("FPS: " + fps);
	}
	
	public static long getFrameCount()
	{
		return frame_count;
	}
	
	public static long getDelta()
	{
		return delta;
	}

	public static long getLast()
	{
		return last;
	}

	public static long getFps()
	{
		return fps;
	}

	public static void setWindow(Window window)
	{
		EngineController.window = window;
	}

	public static Window getWindow()
	{
		return window;
	}
}
